import { useEffect, useState } from 'react';
import { getClosestMultipleOfFour } from './utils';

/**
 * 自定义 Hook，用于在地图上创建并管理热力图
 * @param AMap - 高德地图的 AMap 对象
 * @param map - 地图实例
 * @param data - 用于绘制热力图的数据
 * @param configs - 热力图的配置项
 * @param max - 数据集中的最大值，用于归一化热力图颜色
 * @returns 热力图实例
 */

const useHeatMap = (AMap: any, map: any, configs = {}) => {
  const [heatMap, setHeatMap] = useState<any | null>(null);

  const setHeatMapData = (data: any[], max = 100) => {
    if (heatMap) {
      const max = getClosestMultipleOfFour(Math.max(...data.map(item => item.count)));

      // if (max <= 20) {
      if (max < 4) {
        heatMap.setOptions({
          gradient: {
            1: '#ff0000',
            0.0: '#ff0000',
          },
        });
      } else {
        heatMap.setOptions({
          gradient: {
            // 1: '#ff594c',
            // 0.75: '#ff922e',
            // 0.5: '#fad337',
            // 0.25: '#4dcb73',
            1: '#ff0000',
            0.75: '#ffa500',
            0.5: '#fad337',
            0.25: '#4dcb73',
            // 0.5: '#ffff00',
            // 0.25: '#008000',
          },
        });
      }

      heatMap.setDataSet({
        data,
        max,
      });
    }
  };

  useEffect(() => {
    if (AMap && map) {
      const heatMap = new AMap.HeatMap(map, {
        zIndex: 2,
        radius: 30,
        opacity: [0, 1],
        gradient: {
          1: 'red',
          0.75: '#ffea00',
          0.5: 'rgb(0, 255, 0)',
          0.25: 'blue',
        },
        ...configs,
      });

      setHeatMap(heatMap);
    }
  }, [AMap, map]);

  return { heatMap, setHeatMapData };
};

export default useHeatMap;
